package com.myproject.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import sun.security.util.Password;
@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
        //在 Spring Security 中，用来处理身份认证的类是 AuthenticationManager，我们也称之为认证管理器。
        //而AuthenticationManagerBuilder用来生成一个AuthenticationManager，
        //passwordEncoder需要一个BCryptPasswordEncoder，即下面这个方法生成一个BCryptPasswordEncoder返回给AuthenticationManagerBuilder
    }


    @Bean
    PasswordEncoder password(){
        return new BCryptPasswordEncoder();//生成一个BCryptPasswordEncoder创个上面的passwordEncoder
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/")//设置登录页面
                .loginProcessingUrl("/user/login")//表单传递的地址，即action
                .defaultSuccessUrl("/emps").permitAll()//登录成功跳转地址
                .and().authorizeRequests().antMatchers("/").permitAll()//放行的页面，一般登录页面需要放行
                .anyRequest().authenticated()//任何请求都必须经过身份验证，否则返回401响应
                .and().csrf().disable()//Cross-site request forgery跨站请求伪造，也被称为“One Click Attack”或者Session Riding，
                    // 通常缩写为CSRF或者XSRF，是一种对网站的恶意利用。为了防止跨站提交攻击，通常会配置csrf。但也会影响性能，可自由选择开启或关闭
        ;
        http.logout().logoutUrl("/user/logout")//注销
                .logoutSuccessUrl("/").permitAll();
    }
}
